package com.jp.knowledge.util;


import java.security.MessageDigest;
import java.util.Iterator;
import java.util.Map;
import java.util.TreeMap;
/**
 * 接口签名统一验证工具
 */
public class SignVerifyUtil {

//	private static Logger logger = Logger.getLogger(SignVerifyUtil.class);

	public static boolean checkSign(Map param) {
		if (param == null || param.size() <= 0) {
			return false;
		}
		try {
			Map sortMap = new TreeMap(param);
			String sign = ((String[]) sortMap.get("sign"))[0];
			StringBuffer sb = new StringBuffer();
			Iterator mapIt = sortMap.keySet().iterator();
			while (mapIt.hasNext()) {
				String key = (String) mapIt.next();
				if (!key.equals("sign")) {
					String value = ((String[]) sortMap.get(key))[0];
					sb.append(key + "=" + value + "&");
				}
			}
			String result = sb.substring(0, sb.length() - 1);
			StringBuffer unicode = new StringBuffer();
			for (int i = 0; i < result.length(); i++) {
				char c = result.charAt(i);
				unicode.append("\\u" + Integer.toHexString(c));
			}

			String md5 = encrypt(unicode.toString());
			return sign.equals(md5);
		} catch (Exception e) {
			L.e("检查签名出错：" + e);
		}
		return false;
	}

	/**
	 * 参数签名
	 * @param param
	 * @return
     */
	public static String sign(Map<String,String> param){
		StringBuffer sb = new StringBuffer();
		for (Map.Entry<String,String> entry:param.entrySet()) {
			String key = entry.getKey();
			String value =  entry.getValue();
			sb.append(key + "=" + value + "&");
		}
		String result = sb.substring(0, sb.length() - 1);
		String md5 = encrypt(result);
		return md5;
	}

	/**
	 * 加密
	 * @param plaintext 明文
	 * @return ciphertext 密文
	 */
	public final static String  encrypt(String plaintext) {
		StringBuffer sb = new StringBuffer();
		for (int i = 0; i < plaintext.length(); i++) {
			char c = plaintext.charAt(i);
			sb.append("\\u" + Integer.toHexString(c));
		}
		plaintext= sb.toString();
		char hexDigits[] = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9',
				'a', 'b', 'c', 'd', 'e', 'f' };
		try {
			byte[] btInput = plaintext.getBytes();
			// 获得MD5摘要算法的 MessageDigest 对象
			MessageDigest mdInst = MessageDigest.getInstance("MD5");
			// 使用指定的字节更新摘要
			mdInst.update(btInput);
			// 获得密文
			byte[] md = mdInst.digest();
			// 把密文转换成十六进制的字符串形式
			int j = md.length;
			char str[] = new char[j * 2];
			int k = 0;
			for (int i = 0; i < j; i++) {
				byte byte0 = md[i];
				str[k++] = hexDigits[byte0 >>> 4 & 0xf];
				str[k++] = hexDigits[byte0 & 0xf];
			}
			return new String(str);
		} catch (Exception e) {
			return null;
		}
	}

}
